<template>
  <div class="base-station">
    <div class="base-detail">
      <h2>{{ baseInfo.name }}</h2>
      <div>
        <span class="item" :title="`SN码：${baseInfo.sn}`">{{
          `SN码：${baseInfo.sn}`
        }}</span>
        <el-popover
          v-if="baseInfo.classList.length >= 2"
          placement="top-start"
          title=""
          width="200"
          trigger="hover"
        >
          <div
            v-for="(item, ind) in baseInfo.classList"
            :key="item.className + ind"
          >
            {{ item.className }}
          </div>
          <span
            class="item"
            slot="reference"
            v-html="`绑定班级：${handleClassName(baseInfo.classList)}`"
            ></span
          >
        </el-popover>
        <span
          v-else
          class="item"
          :title="`绑定班级：${handleClassName(baseInfo.classList, true)}`"
          v-html="`绑定班级：${handleClassName(baseInfo.classList)}`"
          ></span
        >
        <span class="item" :title="`简介：${baseInfo.desc || ''}`">{{
          `简介：${baseInfo.desc || ''}`
        }}</span>
      </div>
    </div>
    <div class="m-h3-btn-box border margin-top30">
      <h3 class="fl">
        答题器
      </h3>
      <div class="u-btn-box">
        <el-button
          type="primary"
          @click="onAdd"
          size="small"
          :disabled="!canAddAm"
          >添加答题器</el-button
        >
        <el-button type="primary" @click="onDownloadModule" size="small"
          >下载导入模板</el-button
        >
        <el-button
          type="primary"
          class="u-btn"
          @click="onImportList"
          size="small"
          :disabled="!canAddAm"
          >导入答题器<updateFile
            v-if="canAddAm"
            updata-id="amimport"
            accpetObj="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            @updata="(file) => importAmObj(file[0].files)"
        /></el-button>
        <el-button
          type="primary"
          :disabled="baseAmList.length === 0"
          @click="onExportList"
          size="small"
          >导出答题器</el-button
        >
        <el-button type="primary" @click="onDelAll" size="small"
          >全部删除</el-button
        >
      </div>
    </div>
    <div class="base-station-search">
      <el-form label-width="100px" :model="searchParams" :inline="true">
        <el-form-item label="答题器SN码">
          <el-input
            v-model.trim="searchParams.sn"
            @keyup.enter.native="onSearch"
            placeholder="请输入答题器SN码"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch" size="small"
            >搜索</el-button
          >
          <el-button type="primary" @click="onReset" size="small"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <div class="nice-table">
        <el-table :data="baseAmList" :border="true">
          <el-table-column type="index" label="序号" width="100">
          </el-table-column>
          <el-table-column prop="sn" label="答题器SN码"></el-table-column>
          <el-table-column label="操作" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button size="small" type="text" @click="onDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="pagination.pageNum"
          :page-size="pagination.pageSize"
          layout="total,sizes, prev, pager, next, jumper "
          :total="pagination.total || 0"
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      title="添加答题器"
      :close-on-click-modal="false"
      :visible.sync="visible"
      custom-class="edit-base-station__dialog"
      width="600px"
      @close="onCancel"
    >
      <el-table
        class="dtqTable"
        :data="tableData"
        style="width: 100%"
        max-height="400"
      >
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column label="答题器SN码" width="400">
          <template slot-scope="scope">
            <div class="input-info">
              <el-input
                :class="scope.row.error ? 'red' : ''"
                v-model.trim="scope.row.sn"
                minlength="6"
                maxlength="20"
                placeholder="请输入答题器SN码"
                @blur="validSN(scope.$index)"
                @input="onInput(scope.$index)"
                @focus="scope.row.error = ''"
                clearable
              ></el-input>
            </div>
            <div class="err-info">
              {{ scope.row.error }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-button class="add-btn" @click="addAmList">添加一条</el-button>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onCancel" size="small">取消</el-button>
        <el-button
          type="primary"
          @click="onSubmit"
          size="small"
          v-preventReClick
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  baseStationAmList,
  delBaseStationAm,
  getBaseStationDetail,
  addBaseStationAm,
  baseStationImportModule,
  baseStationImportAmlist,
  baseStationEmportAmlist,
  baseStationDelAllAmlist,
} from '@/api/baseStation.js';
import { ERROR_CODE } from '@/api/api.js';

export default {
  name: 'base-station-detail',
  data() {
    return {
      searchParams: {
        sn: '',
      },
      baseInfo: {
        baseStationId: '',
        name: '',
        sn: '',
        desc: '',
        classList: [],
        bindAmNum: 0,
      },
      baseAmList: [],
      pagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleCurrentChange,
        handleSizeChange: this.handleSizeChange,
      },
      visible: false,
      // 默认三条
      tableData: [
        {
          sn: '',
          error: '',
        },
        {
          sn: '',
          error: '',
        },
        {
          sn: '',
          error: '',
        },
      ],
    };
  },
  components: {
    updateFile: (resolve) => require(['@/components/updateFile.vue'], resolve),
  },
  activated() {
    this.$nextTick(() => {
      this.searchParams = {
        sn: '',
      };
      this.getBaseDetail((data) => {
        if (data.data && data.code === 0) {
          this.baseInfo = data.data;
        }
      });
      this.getList();
    });
  },
  computed: {
    baseStationId() {
      return this.$route.query.id;
    },
    schoolId() {
      return this.$route.query.schoolId;
    },
    // 是否可导入或新增答题器（对一个基站添加答题器、导入答题器的时候设置答题器数量上限为60）
    canAddAm() {
      return this.pagination.total < 60;
    },
  },
  methods: {
    handleClassName(classList, flag) {
      if (!classList || !classList.length) {
        return '';
      }
      if (flag) {
        return classList.map((classItem) => classItem.className).join('、');
      }

      let classString = '';
      let classNames = [];
      classList.slice(0, 1).forEach((classItem) => {
        classNames.push(classItem.className);
      });

      classString = classNames.join('、').substr(0, 6);
      if (classList.length > 1) {
        classString = `${classString}等<span class="number">${classList.length}</span>个班级`;
      }
      return classString;
    },
    downloadFile(url, fileName) {
      const link = document.createElement('a'); // 创建一个a元素
      link.herf = url; // 设置a元素的目标url
      link.download = fileName; // 设置下载的文件名。该属性的意思是当点击时不是导航到目标url而是下载，接受一个文件名。
      link.style.display = 'none'; // 设置a元素不可见
      document.body.appendChild(link); // 将a元素插入到页面中
      link.click(); // 触发a元素的点击事件，实现下载
      document.body.removeChild(link); // 在页面中删除a元素
    },
    async importAmObj(file) {
      console.log(file);
      let formData = new FormData();
      formData.append('file', file);
      formData.append('schoolId', this.schoolId);
      formData.append('baseStationId', this.baseStationId);

      let res = await baseStationImportAmlist(formData);
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (!data.data.hadImported) {
        return this.$confirm(
          '表格中存在部分信息错误，请下载修改后重新上传',
          '提示',
          {
            confirmButtonText: '下载',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            let url = data.data.url;
            if (url) {
              // this.downloadFile(url, file.name)
              window.open(url);
            } else {
              this.$message.info('文件地址不存在');
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            });
          });
      }
      if (data && data.code === 0) {
        this.$message.success('导入成功！');
        this.onReset();
      } else {
        this.$message.error(data.msg);
      }
    },
    formatDate() {
      let Dates = new Date();
      let Y = Dates.getFullYear();
      let M = Dates.getMonth() + 1;
      let D = Dates.getDate();
      let times = Y + (M < 10 ? '0' : '') + M + (D < 10 ? '0' : '') + D;
      return times;
    },formatDate() {
      let Dates = new Date();
      let Y = Dates.getFullYear();
      let M = Dates.getMonth() + 1;
      let D = Dates.getDate();
      let times = Y + (M < 10 ? '0' : '') + M + (D < 10 ? '0' : '') + D;
      return times;
    },
    async onDownloadModule() {
      let res = await baseStationImportModule({
        schoolId: this.schoolId,
      });
      if (res.status === 200) {
        let date = this.formatDate();
        let filename = decodeURI(`答题器导入-${date}.xlsx`);
        filename = filename.replace(/\"/g, '');
        this.$downloadExcel(res.data, filename);
      }
    },
    onImportList() {},
    onExportList() {
      this.getBaseDetail(async () => {
        let params = this.cloneSearchParams || this.searchParams;
        let res = await baseStationEmportAmlist({
          schoolId: this.schoolId,
          baseStationId: this.baseStationId,
          sn: params.sn,
        });
        if (res.status === 200) {
          let date = this.formatDate();
          let filename = `${this.baseInfo.name}-${date}.xlsx`;
          filename = filename.replace(/\"/g, '');
          this.$downloadExcel(res.data, filename, false);
        }
      });
    },
    onDelAll() {
      this.$confirm('确认删除全部答题器？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          baseStationDelAllAmlist({
            schoolId: this.schoolId,
            baseStationId: this.baseStationId,
          }).then((res) => {
            if (res[0]) {
              return;
            }
            let data = res[1];
            if (data && data.code === 0) {
              this.$message.success('删除成功！');
              this.getList();
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch((e) => {
          console.log('删除失败！', e);
        });
    },
    validSN(index) {
      let curValue = this.tableData[index].sn;
      if (!curValue) {
        // this.tableData[index].error = 'SN码不能为空！';
        return;
      }
      if (curValue.length < 6 || curValue.length > 20) {
        this.tableData[index].error = '请输入6-20字符！';
        return;
      }
      let _index = this.tableData.findIndex((item) => item.sn === curValue);
      if (_index > -1 && _index !== index) {
        this.tableData[index].error = 'SN码不能重复！';
      } else {
        this.tableData[index].error = '';
      }
    },
    onInput(index) {
      let val = this.tableData[index].sn;
      val = val.replace(/[^a-zA-Z0-9]/g, '');
      this.tableData[index].sn = val;
    },
    onAdd() {
      this.visible = true;
    },
    onCancel() {
      this.tableData = this.$options.data().tableData;
      this.visible = false;
    },
    validData() {
      this.tableData.forEach((item, index) => {
        this.validSN(index);
      });
      let errorArr = this.tableData.filter((item) => item.error);
      if (errorArr.length) {
        return false;
      }
      return true;
    },
    onSubmit() {
      let validflag = this.validData();
      if (!validflag) return this.$message.info('请检查表单数据');
      let tableData = this.tableData.filter(item => item.sn);
      if (!tableData.length) {
        return this.$message.info('请至少保留一条记录');
      }
      // 数据校验
      addBaseStationAm({
        schoolId: this.schoolId,
        baseStationId: this.baseStationId,
        amSnList: tableData.map((item) => item.sn),
      }).then((res) => {
        if (res[0]) {
          return;
        }
        let data = res[1];
        if (data && data.code == 0) {
          // 异常处理
          if (data.data && data.data.errorBind && data.data.errorBind.length) {
            console.log('data.data.errorBind', data.data.errorBind);
            data.data.errorBind.forEach((errItem) => {
              this.tableData.forEach((item) => {
                if (item.sn === errItem.sn) {
                  item.error = errItem.message;
                }
              });
            });
          } else {
            this.$message.success('添加成功');
            this.visible = false;
            this.onReset();
          }
        }
      });
    },
    addAmList() {
      this.tableData.push({
        sn: '',
        error: '',
      });
      // 定位到新添加的一条数据
      this.$nextTick(() => {
        let index = this.tableData.length - 1;
        let lastDom = document
          .getElementsByClassName('dtqTable')[0]
          .getElementsByClassName('el-table__row')[index];
        lastDom && lastDom.scrollIntoView();
      });
    },
    handleDelete(index, row) {
      this.tableData.splice(index, 1);
    },
    async getList() {
      let res = await baseStationAmList({
        schoolId: this.schoolId,
        baseStationId: this.baseStationId,
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        ...this.searchParams,
      });
      this.cloneSearchParams = this.$deepcopy(this.searchParams);
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (data && data.code === 0) {
        if (
          data.data.totalPage > 0 &&
          data.data.totalPage < data.data.currPage
        ) {
          this.handleCurrentChange(data.data.totalPage);
        } else {
          this.pagination.total = data.data.totalCount;
          this.baseAmList = data.data.list;
        }
      } else {
        this.$message.error(data.msg);
      }
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val;
      this.getList();
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.getList();
    },
    onSearch() {
      this.pagination.pageNum = 1;
      this.getList();
    },
    onReset() {
      this.pagination.pageNum = 1;
      this.searchParams = {
        sn: '',
      };
      this.getList();
    },
    getBaseDetail(callback) {
      getBaseStationDetail({
        schoolId: this.schoolId,
        baseStationId: this.baseStationId,
      }).then((res) => {
        if (res[0]) {
          if (res[1].code === ERROR_CODE.REFRESH_LIST) {
            this.$router.push({
              name: 'school-detail',
              params: { id: this.schoolId },
            });
          }
          return;
        }
        let data = res[1];

        if (callback) {
          callback(data);
        }
      });
    },
    onDelete(row) {
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delBaseStationAm({
            schoolId: this.schoolId,
            baseStationId: this.baseStationId,
            relatedId: row.relatedId,
          }).then((res) => {
            if (res[0]) {
              return;
            }
            let data = res[1];
            if (data && data.code === 0) {
              this.$message.success('操作成功！');
              this.getList();
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch((e) => {
          console.log('操作失败！', e);
        });
    },
  },
};
</script>
<style scoped>
.base-detail span.item {
  display: inline-block;
  width: 30%;
  margin-right: 2%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
/deep/ .el-dialog__body {
  height: 500px;
}
.u-btn {
  font-size: 12px;
  position: relative;
}
.input-info {
  width: 350px;
  /* display: inline-block; */
}
/deep/ .input-info .red {
  border: 1px solid red;
  border-radius: 5px;
}
.err-info {
  /* display: inline-block; */
  width: 220px;
  color: red;
  padding: 5px 0 0 8px;
}
.add-btn {
  margin-top: 20px;
}
</style>
